package cn.jfinalbbs.hnair;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.jfinalbbs.common.BaseController;
import cn.jfinalbbs.hnair.json.Hnair;
import cn.jfinalbbs.hnair.json.Hnair.Attribute;
import cn.jfinalbbs.hnair.json.Hnair.Entry;
import cn.jfinalbbs.hnair.json.Hnair.Farefamily;
import cn.jfinalbbs.hnair.json.Hnair.Farefamilycontent;
import cn.jfinalbbs.hnair.json.Hnair.Flight;
import cn.jfinalbbs.hnair.json.Hnair.Flightinformation;
import cn.jfinalbbs.hnair.json.Hnair.Flightitinerarypricepoint;
import cn.jfinalbbs.hnair.json.Hnair.Flightitinerarypricepoints;
import cn.jfinalbbs.hnair.json.Hnair.Flightsegment;
import cn.jfinalbbs.hnair.vo.FlightVo;
import cn.jfinalbbs.hnair.vo.RulesVo;
import cn.jfinalbbs.interceptor.AdminUserInterceptor;
import cn.jfinalbbs.utils.DateUtil;
import cn.jfinalbbs.utils.HttpClientUtil;
import cn.jfinalbbs.utils.MD5;

import com.google.gson.Gson;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.qq.connect.utils.json.JSONException;
import com.qq.connect.utils.json.JSONObject;

@Before(AdminUserInterceptor.class)
public class HnairController extends BaseController {
	
	private String url1 = "http://114.251.242.135:8080/gxotarest/api/search-low-fare-trips.json";
	private String url2 = "http://114.251.242.135:8080/gxotarest/api/calculate-trip.json";
	private String url3 = "http://114.251.242.135:8080/gxotarest/api/verify-trip.json";
	
	private String charset = "utf-8";
	private HttpClientUtil httpClientUtil = null;
	
	String OTACode = "GXAIRLINES_120";//OTACode
	String ip = "220.249.72.237";//签名IP
	String key = "69CDDG7D0042E4C672F46F0BACGAE3H2";//key
	Long timestamp = System.currentTimeMillis();//时间戳
	
	public HnairController(){
		httpClientUtil = new HttpClientUtil();
	}
	
    /**
     * 海航航空首页
     */
    public void index() {
    	render("index.html");
    }
    
    /**
     * 查询最低票价 -- 第一步
     */
    public void search() {
    	String name = getPara("go_back");//往返1 /单程  0
    	String go = getPara("go");//出发机场三字码
    	String back = getPara("back");//目的地机场三字码
    	String go_back_date = getPara("go_back_date");//往返日期
    	String sigle_date = getPara("sigle_date");//单程日期
    	String cabin = getPara("Economy");//经济舱
    	String promotion = getPara("promotion");//促销代码
    	String flexible = getPara("flexible");//是否灵活搜索
    	String adult = getPara("adult");//成人
    	String child = getPara("child");//儿童
    	String baby = getPara("baby");//婴儿
    	
    	
		Map<String,String> createMap = new HashMap<String,String>();

    	/**
    	 *  根据选择的成人儿童婴儿来生成多组旅客类型
    	 */
		List<HnairVo> listStr = new ArrayList<HnairVo>();
    	if(StringUtils.isNotEmpty(adult)){
    		Integer adultNum = Integer.parseInt(adult);
    		if(adultNum != 0){
    			for (int i = 0; i < adultNum; i++) {
    				String adultData = "code:" + "ADT";//成人
    				HnairVo vo = new HnairVo();
    				vo.setPostContent(adultData);
    				vo.setPostName("traveler");
    				listStr.add(vo);
				}
    		}
    	}
    	
    	if(StringUtils.isNotEmpty(child)){
    		Integer childNum = Integer.parseInt(child);
    		if( childNum != 0){
    			for (int i = 0; i < childNum; i++) {
    				String childData = "code:" + "CNN";//儿童
        			HnairVo vo = new HnairVo();
    				vo.setPostContent(childData);
    				vo.setPostName("traveler");
    				listStr.add(vo);
				}
    		}
    	}
    	
    	if(StringUtils.isNotEmpty(baby)){
    		Integer babyNum = Integer.parseInt(baby);
    		if( babyNum != 0){
    			for (int i = 0; i < babyNum; i++) {
    				String babyData = "code:" + "INF";//婴儿
        			HnairVo vo = new HnairVo();
    				vo.setPostContent(babyData);
    				vo.setPostName("traveler");
    				listStr.add(vo);
				}
    			
    		}
    	}
    	
		appIn(createMap,OTACode,OTACode + ip + timestamp + key,timestamp);
		
		String godate = null;
		String backdate = null;
		List<HnairVo> leglist = new ArrayList<HnairVo>();
		if(StringUtils.isNotEmpty(name)){
			if(Integer.parseInt(name) == 1){//往返
				String[] go_back = StringUtils.trim(go_back_date).split("-");
				if(null!=go_back && go_back.length > 0){
					godate = DateUtil.mmddyyyy2yyyymmdd(go_back[0]);
					backdate = DateUtil.mmddyyyy2yyyymmdd(go_back[1]);
				}
				
				String leggo = "index:"+"0"+";origin:"+ PropKit.use("city.properties").get(go) +";originType:A;destination:"+ PropKit.use("city.properties").get(back) +";destinationType:A;date:"+godate;
				String legback = "index:"+"1"+";origin:"+PropKit.use("city.properties").get(back)+";originType:A;destination:"+ PropKit.use("city.properties").get(go) +";destinationType:A;date:"+backdate;
					HnairVo v1 = new HnairVo();
					v1.setPostName("leg");
					v1.setPostContent(leggo);
					
					HnairVo v2 = new HnairVo();
					v2.setPostName("leg");
					v2.setPostContent(legback);
					
					leglist.add(v1);
					leglist.add(v2);

			}else{//单程
				godate = DateUtil.mmddyyyy2yyyymmdd(sigle_date);
				String leggo = "index:"+"0"+";origin:"+PropKit.use("city.properties").get(go)+";originType:A;destination:"+ back +";destinationType:A;date:"+godate;
				HnairVo v1 = new HnairVo();
				v1.setPostName("leg");
				v1.setPostContent(leggo);
				leglist.add(v1);
			}
		}
		
		searchLowFareTrips(createMap,cabin,flexible,promotion);
		
//		StringBuffer httpOrgCreateTestRtn = read("C:\\Users\\15816\\git\\jfinalbbs\\src\\main\\resources\\search-low-fare-trips.json");
		
		String httpOrgCreateTestRtn = null;
			for (int i = 0; i < 10; i++) {
				 httpOrgCreateTestRtn = httpClientUtil.doPostLowestPrice(url1,createMap,charset,listStr,leglist);
				 System.out.println("第" + (i+1) +  "次查询:" + httpOrgCreateTestRtn);
				 	if(httpOrgCreateTestRtn.indexOf("ServiceError") == -1){//没有发生错误
				 		break;
				 	}else{//发生错误
				 		continue;
				 	}
			}
		try {
			Gson gson = new Gson();
			Hnair nair = gson.fromJson(httpOrgCreateTestRtn.toString(), Hnair.class);
			if(null != nair.getAirlowfaresearchrs()){
				//旅客规则
				if(null != nair.getAirlowfaresearchrs().getFarefamilycontent()){
					Farefamilycontent farefamilycontent = nair.getAirlowfaresearchrs().getFarefamilycontent();
					List<Farefamily> familyList = farefamilycontent.getFarefamily();
					
					List<RulesVo> voList = new ArrayList<RulesVo>();
					for(Farefamily fare : familyList){
						RulesVo vo = new RulesVo();
						
						List<Entry> entryList = fare.getName().getEntry();
						if(null != entryList && entryList.size() == 2){
								String type = entryList.get(1).getValue();
								vo.setType(type);
						}
						
						List<Attribute> ruleList = fare.getAttribute();
						if(null != ruleList && ruleList.size() > 0){
							for (int i = 0; i < ruleList.size(); i++) {
								if(i == 0){
									vo.setBookingFee(ruleList.get(i).getEntry().get(1).getValue());
								}else if(i == 1){
									vo.setRefundFee(ruleList.get(i).getEntry().get(1).getValue());
								}else if( i == 2){
									vo.setBaggageAllowance(ruleList.get(i).getEntry().get(1).getValue());
								}
							}
						}
						voList.add(vo);
					}
					setAttr("ruleslist", voList);
				}
				//两个List  一个为出发地的航班选择 另一个为目的地的航班选择
				Flightitinerarypricepoints points = nair.getAirlowfaresearchrs().getFlightitinerarypricepoints();
				if(null != points){
					List<Flightitinerarypricepoint> pointList = points.getFlightitinerarypricepoint();
					if(null != pointList && pointList.size() > 0){
						
						List<FlightVo> vos = new ArrayList<FlightVo>();
						for(Flightitinerarypricepoint pricePoint : pointList){
							FlightVo flightVo = new FlightVo();
							flightVo.setIndex(pricePoint.getIndex());
							flightVo.setId(pricePoint.getId());
							flightVo.setLeg(pricePoint.getLeg());
							
							boolean stop = false; 
							if(null != nair.getAirlowfaresearchrs().getFlightinformationsummary()){
								List<Flightinformation> infomationList = nair.getAirlowfaresearchrs().getFlightinformationsummary().getFlightinformation();
								if(null != infomationList && infomationList.size() > 0 && !stop) {
									for (Flightinformation information : infomationList) {
										List<Flight> flightList = information.getFlight();
										if(null != flightList && flightList.size() > 0){
											for(Flight flight : flightList){
												List<Flightsegment> segmentList = flight.getFlightsegment();
												if(null != segmentList && segmentList.size() > 0){
													for(Flightsegment segment : segmentList){
														if(segment.getId().equals(pricePoint.getFlightinformationattributes().get(0).getFlightsegmentref())){
															flightVo.setArrivalDate(segment.getArrivaldate());
															flightVo.setDepartureDate(segment.getDeparturedate());
															flightVo.setEquipmentCode(segment.getEquipmentcode());
															flightVo.setMaarketingAirline(segment.getMarketingairline());
															flightVo.setFlightNumber(segment.getFlightnumber());
															stop = true;  
											                break;  
														}
													}
												}
											}
										}
										
									}
								}
							}
							vos.add(flightVo);
						}
						setAttr("flightlist", vos);
					}
				}
				
				System.out.println("-------计算税费-----------");
		    	Map<String,String> createMap2 = new HashMap<String,String>();
		    	timestamp = System.currentTimeMillis();
		    	appIn(createMap2,OTACode,OTACode + ip + timestamp + key,timestamp);
		    	createMap2.put("searchId",nair.getAirlowfaresearchrs().getUri());
		    	createMap2.put("index", String.valueOf(nair.getAirlowfaresearchrs().getFlightitinerarypricepoints().getFlightitinerarypricepoint().get(0).getIndex()));
		    	String rtn = httpClientUtil.doPost(url2,createMap2,charset);
		    	
		    	System.out.println(rtn);
		    	
		    	
		    	System.out.println("-----------验证价格是否合理--------------");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		render("list.html");
    }
    
    /**
      * 读取本地文件
      * @author: liuwangpan
      * @createTime: 2016年3月9日  下午8:31:26
     */
    public static StringBuffer read(String file) {
		   String s = null;
		   StringBuffer sb = new StringBuffer();
		   List<String> zhanghaos = new ArrayList<String>();
		   File f = new File(file);
		   if (f.exists()) {
		    try {
		     BufferedReader br = new BufferedReader(new InputStreamReader(
		       new FileInputStream(f)));
		     while ((s = br.readLine()) != null) {
		      sb.append(s);
		      zhanghaos.add(s);
		     }
		     
		    } catch (Exception e) {
		     e.printStackTrace();
		    }
		    return sb;
		   }else{
		    return null;
		   }
		}
    
    
    /**
      *  计算税费 ----- 》 第二步
      *  使用ajax将选中的航班index传过去  外加之前跳转到列表页面保存的@uri结果
      * @author: liuwangpan
      * @createTime: 2016年3月9日  下午3:44:00
     */
    public void selectflight(){
    	
    	System.out.println("-------计算税费-----------");
    	Map<String,String> createMap2 = new HashMap<String,String>();
    	timestamp = System.currentTimeMillis();
    	appIn(createMap2,OTACode,OTACode + ip + timestamp + key,timestamp);
    	createMap2.put("searchId","56e26ecee4b052676a3a155a");
    	createMap2.put("index","1");
    	String rtn = httpClientUtil.doPost(url2,createMap2,charset);
    	
    	System.out.println(rtn);
    	//TODO 往返航班多传一个index 也就是用户在页面上可以选择两个index 往返航班
//    	renderJson(httpOrgCreateTestRtn);
    }
    
	/**
	 * 计算税费 -----> 第三步 验证票价是否合理
	 * @author: liuwangpan
	 * @createTime: 2016年3月9日 下午3:44:00
	 */
	public void verifyTrips() {
		String tripId = getPara("tripId");
		Map<String, String> createMap = new HashMap<String, String>();
		appIn(createMap, OTACode, OTACode + ip + timestamp + key, timestamp);
		createMap.put("tripId", tripId);
		String httpOrgCreateTestRtn = httpClientUtil.doPost(url3, createMap,
				charset);
		renderJson(httpOrgCreateTestRtn);
	}
    
    /**
	 *  请求头
	  * @author: liuwangpan
	  * @createTime: 2016年3月8日  下午4:49:14
	 */
	public void appIn(Map<String,String> createMap,String OTACode,String token,Long timestamp){
		createMap.put("ln","zh_CN");
		createMap.put("OTACode",OTACode);
		createMap.put("token",MD5.MD5Encode(token));
		createMap.put("timestamp",timestamp.toString());
	}
	
	/**
	  * 查询最低票价
	  * @author: liuwangpan
	  * @createTime: 2016年3月8日  下午4:53:00
	 */
	public void searchLowFareTrips(Map<String,String> createMap,String cabin,String flexible,String promotion){
		//traveler 在其他地方做处理  可以多个  leg可以为两个 在上面处理
		
		if(StringUtils.isNotEmpty(promotion)){
    		createMap.put("flexible",flexible);//灵活日期选择
    	}
		
		if(StringUtils.isNotEmpty(cabin)){
			createMap.put("cabin", cabin);//经济舱 必选
		}else{
			throw new RuntimeException("不能为空");
		}
		
		if(StringUtils.isNotEmpty(promotion)){
    		String promotionData = "code:" + promotion;//促销代码 可选
    		createMap.put("promotion",promotionData);
    	}
	}

}